package OrderService

import (
	"context"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	"gdshop-back-end-go/service-other/GoodsActivityService"
)

// 自动选择最优惠的活动，只允许从商品详情创建
func goodsActivityByCreateByGroup(ctx context.Context, createModel *OrderResp.OrderItem) error {
	//g.Dump(createModel.Goodss)

	var discountMoney int64 = 0
	for _, item := range createModel.Goodss {
		activitys, err := GoodsActivityService.GetGoodsActivityByGoodsId(ctx, int(item.Id))
		if err != nil {
			return err
		}
		// 判断，防止没有活动
		if len(activitys) < 1 {
			continue
		}
		activity, tmpDm, err := GoodsActivityService.GetMaxDiscountActivity(activitys, item.Paid)
		if err != nil {
			return err
		}

		// 如果 activity = nil 说明没有匹配到
		if activity == nil {
			continue
		}

		//tmpDm := item.Paid - int64(float64(item.Paid)*activitys[0].DiscountRatio)
		discountMoney += tmpDm
		item.Paid -= tmpDm
		item.ActivityPaid = item.Paid
		item.ActivityId = activity.Id
		item.ActivityDiscountMoney = tmpDm
	}

	createModel.ActivityDiscountMoney = discountMoney

	return nil
}
